package cloud.xlh.digital_power_order.task;

import cloud.xlh.digital_power_order.util.SnowflakeIdFactory;
import cloud.xlh.digital_power_order.util.cache.OrderRedisOperateServiceImpl;
import cloud.xlh.infrastructure.enums.CacheComponentEnum;
import cn.hutool.extra.spring.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/8/12 12:13
 * @ Description:
 */
public class GenOrderNoTimerTask extends TimerTask {
    private static final Logger logger = LoggerFactory.getLogger(GenOrderNoTimerTask.class);
    @Override
    public void run() {
        genOrderNo();
    }

    private static final String ORDER_NO_KEY = "OrderNo";

    //每秒生成订单号个数
    private static final int genSumEverySeconds = 100;

    private void genOrderNo() {
        OrderRedisOperateServiceImpl orderRedisOperateService = SpringUtil.getBean(CacheComponentEnum.ORDER_REDIS.getBeanName());
        //控制1s生成100个订单号 1708322642144268288 19位
        SnowflakeIdFactory idWorker = new SnowflakeIdFactory(1, 2);
        long start = System.currentTimeMillis();
        int count = 0;
        for (long end = System.currentTimeMillis(); end - start < 1000 ; count++ , end = System.currentTimeMillis()) {
            if (count > genSumEverySeconds - 1) {
                break;
            }
            orderRedisOperateService.addOrderNoToSortCollection(ORDER_NO_KEY , String.valueOf(idWorker.nextId()));
        }
        Long orderNoSum = orderRedisOperateService.calculateOrderNoSumFromSortCollection(ORDER_NO_KEY);
        logger.info("已生成订单号总数：{}" , orderNoSum);
    }

    /*public static void main(String[] args) {
        //控制1s生成100个订单号 1708322642144268288 19位
        SnowflakeIdFactory idWorker = new SnowflakeIdFactory(1, 2);
        long start = System.currentTimeMillis();
        int count = 0;
        for (long end = System.currentTimeMillis() ; end - start < 1000 ; count++) {
            if (count > 100) {
                break;
            }
            System.out.println(idWorker.nextId());

        }
    }*/
}
